package com.example.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.gateway.vo.ErrorResult;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 校验权限示例
 * @see org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory
 * @author hmy
 */
@Component
public class PermissionCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<PermissionCheckGatewayFilterFactory.Config> {

    public PermissionCheckGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("enabled");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                System.out.println("********** permission filter **********");
                System.out.println("开始校验权限");
                System.out.println("********** permission filter **********");
                if(config.isEnabled()){
                    String token = exchange.getRequest().getQueryParams().getFirst("token");
                    if(token == null || token.isEmpty()){
                        exchange.getResponse().getHeaders().add("Content-Type", "application/json");
                        ServerHttpResponse response = exchange.getResponse();
                        response.setStatusCode(HttpStatus.FORBIDDEN);
                        ErrorResult result = new ErrorResult();
                        result.setCode(403);
                        result.setMsg("没有权限");
                        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result, SerializerFeature.WriteMapNullValue).getBytes());
                        return response.writeWith(Flux.just(dataBuffer));
                    }
                }
                return chain.filter(exchange);
            }
        };
    }

    public static class Config{
        private boolean enabled;

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }
}
